﻿using System;
using System.ComponentModel;
using System.ServiceProcess;
using System.Threading;
using System.Windows.Forms;

namespace CS.WinServiceManager
{
    public partial class MainFrom : Form
    {
        public MainFrom()
        {
            InitializeComponent();
        }

        private string _servicePath;
        private string _serviceName;
        private string _serviceDisplayName;
        private string _serviceDescription;
        private bool _isConfiged;
        private ServiceController _service;

        /// <summary>
        /// 主Form载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFrom_Load(object sender, EventArgs e)
        {
            //未选择服务时不可用
            ButtonEnabled(false);
            txtMessage.Text = "请选择一个Windows服务...";
        }

        /// <summary>
        /// 安装
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInstall_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            if (!_isConfiged) return;
            txtMessage.Text = string.Format("正在安装服务{0}...", _serviceDisplayName);
            ButtonEnabled(false);
            var install = new ServiceInstall();
            var val = install.InstallService(_servicePath, _serviceName, _serviceDisplayName);
            var msg = string.Format("服务{0}安装{{0}}!", _serviceDisplayName);
            if (val)
            {
                ReLoadServiceInfo();
                //Thread.Sleep(1000);
                //_service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 5, 0));
                //ReLoadServiceInfo();
                if (_service != null)
                {
                    txtMessage.Text = string.Format(msg, "成功");
                }
            }
            else
            {
                txtMessage.Text = string.Format(msg, "失败");
            }

            ReLoadServiceInfo();

        }

        /// <summary>
        /// 卸载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUnInstall_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            try
            {
                txtMessage.Text = string.Format("正在卸载服务{0}...", _serviceDisplayName);
                ButtonEnabled(false);

                if(_service.Status == ServiceControllerStatus.Running)
                {
                    _service.Stop();
                    _service.Refresh();
                }

                var install = new ServiceInstall();
                var val = install.UnInstallService(_serviceName);
                var msg = string.Format("服务{0}卸载{{0}}", _serviceDisplayName);
                if (val)
                {
                    //ReLoadServiceInfo();
                    _service.Dispose();
                    _service = null;
                    txtMessage.Text = string.Format(msg, "成功!\r\n注意:可能要重启计算机。");
                    btnInstall.Enabled = true;
                   
                }
                else
                {
                    txtMessage.Text = string.Format(msg, "失败!\r\n请重新打开本工具后再尝试。");
                }

                //ReLoadServiceInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("卸载服务{0}时异常。\r\n{1}", _serviceName, ex.Message + ex.InnerException.Message), "异常提示");
                //throw;
            }
        }

        /// <summary>
        /// 文件选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            openFileDialog.ShowDialog();
        }
        /// <summary>
        /// 文件选择成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            var serviceFullPath = openFileDialog.FileName;
            txtServiceFullPath.Text = serviceFullPath;
            ReLoadServiceInfo();
        }

        /// <summary>
        /// 再次载入配置信息
        /// </summary>
        void ReLoadServiceInfo()
        {
            _servicePath = txtServiceFullPath.Text;
            if (string.IsNullOrEmpty(_servicePath))
            {
                _isConfiged = false;
                txtMessage.Text = string.Format("请选择一个Windows服务...");
                return;
            }
            try
            {
                var configInfo = new ServiceInfo(_servicePath);
                txtServiceName.Text = configInfo.ServiceName;
                txtServiceDisplayName.Text = configInfo.DisplayName;
                txtServiceDescription.Text = configInfo.Description;
                _serviceName = configInfo.ServiceName;
                _serviceDisplayName = configInfo.DisplayName;
                _serviceDescription = configInfo.Description;
            }
            catch (Exception ex)
            {
                _isConfiged = false;
                MessageBox.Show(string.Format("配置错误。\r\n异常:{0}", ex.Message));
                //throw;
            }

            if (string.IsNullOrEmpty(_serviceName) || string.IsNullOrEmpty(_serviceDisplayName))
            {
                _isConfiged = false;
                txtMessage.Text = string.Format("{0}服务名称和显示名配置错误。", _serviceDisplayName);
            }
            else
            {
                _isConfiged = true;
            }

            //配置正确后的反应
            _service = GetMatchService();
            if (_service == null)
            {
                btnInstall.Enabled = true;
                btnUnInstall.Enabled = false;
                txtMessage.Text = string.Format("可以安装{0}服务了。", _serviceDisplayName);
            }
            else
            {
                _service.Refresh();

                btnUnInstall.Enabled = true;
                btnInstall.Enabled = false;
                txtMessage.Text = string.Format("可以卸载{0}服务了。", _serviceDisplayName);



                btnStop.Enabled = _service.Status == ServiceControllerStatus.Running || _service.Status == ServiceControllerStatus.Paused ? true : false;
                btnStart.Enabled = _service.Status == ServiceControllerStatus.Stopped ? true : false;
                if (!_service.CanPauseAndContinue)
                {
                    btnPause.Enabled = false;
                    btnResume.Enabled = false;
                }
                else
                {
                    btnPause.Enabled = _service.Status == ServiceControllerStatus.Running ? true : false;
                    btnResume.Enabled = _service.Status == ServiceControllerStatus.Paused ? true : false;
                }

                txtMessage.Text = string.Format("可以操作{0}服务了。", _serviceDisplayName);
            }
        }

        /// <summary>
        /// 找到正在服役的服务。
        /// </summary>
        /// <returns></returns>
        ServiceController GetMatchService()
        {
            var services = ServiceController.GetServices();
            foreach (var service in services)
            {
                if (service.ServiceName == _serviceName && service.DisplayName == _serviceDisplayName)
                {
                    return service;
                }
                continue;
            }
            return null;
        }

        void ButtonEnabled(bool b)
        {
            btnUnInstall.Enabled = b;
            btnInstall.Enabled = b;
            btnStart.Enabled = b;
            btnStop.Enabled = b;
            btnPause.Enabled = b;
            btnResume.Enabled = b;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            if (_service == null)
            {
                txtMessage.Text = string.Format("服务{0}未正确安装", _serviceName);
                return;
            }

            try
            {
                _service.Start();
                txtMessage.Text = string.Format("正在启动服务{0}...", _serviceName);
                _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 5, 0));
                txtMessage.Text = string.Format("服务{0}已开始运行。", _serviceName);

                ReLoadServiceInfo();
            }
            catch (Exception ex)
            {
                _service.Dispose();
                _service = null;
                MessageBox.Show(string.Format("试图停止{0}时异常。\r\n{1}", _serviceName, ex.InnerException.Message), "异常提示");
                //throw;
                ReLoadServiceInfo();
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            if (_service == null)
            {
                txtMessage.Text = string.Format("服务{0}未正确安装", _serviceName);
                return;
            }
            _service.Stop();
            txtMessage.Text = "正在停止服务...";
            _service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 5, 0));

            txtMessage.Text = string.Format("服务{0}已停止运行。", _serviceName);

            ReLoadServiceInfo();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            if (_service == null)
            {
                txtMessage.Text = string.Format("服务{0}未正确安装", _serviceName);
                return;
            }
            _service.Pause();
            txtMessage.Text = "正在暂停服务...";
            _service.WaitForStatus(ServiceControllerStatus.Paused, new TimeSpan(0, 0, 5, 0));

            txtMessage.Text = string.Format("服务{0}运行已挂起。", _serviceName);
            ReLoadServiceInfo();
        }

        private void btnResume_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
            if (!_isConfiged) return;

            if (_service == null)
            {
                txtMessage.Text = string.Format("服务{0}未正确安装", _serviceName);
                return;
            }
            _service.Continue();
            txtMessage.Text = "正在恢复服务...";
            _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 5, 0));

            txtMessage.Text = string.Format("服务{0}已恢复运行。", _serviceName);
            ReLoadServiceInfo();
        }

        /// <summary>
        /// 刷新服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ReLoadServiceInfo();
        }


    }
}
